import {Component} from 'react';
import React from 'react';
import {connect} from 'umi';
import HighPerformTable from '@/components/HighPerformTable';
import APIS from '@/apis';
import FilterByStatistics from '@/components/FilterByStatistics';
import moment from "moment";
import {FormatTime} from "@/utils/utils";
import {Button, DatePicker, Form, message, Select} from "antd";
import Modal from "antd/lib/modal/Modal";
import {DownLoadFile, SUCCESS_CODE} from "@/apis/UtilsAPI";

class LearnStat extends Component<any, any> {
  actionRef: any;
  state = {
    filter: -1,
    allCourse: [],
    allExp: [],
    visible: false,
    disable: false
  }

  componentDidMount() {
    APIS.CourseAPI.GetCourseListInfo({
      current: 1,
      pageSize: 99999,
      state: -1
    }).then(res => this.setState({allCourse: res.data})).catch(e => {
      console.error(e)
    });
    APIS.ExamAPI.GetExpList({current: 1, pageSize: 999}).then((resp) => {
      this.setState({allExp: resp.data});
    }).catch((e) => console.error(e));
    if (localStorage.getItem("disable_time") && localStorage.getItem("disable_time") !== "0") {
      this.setState({disable: true});
      this.interval = setInterval(this.CheckTime, 1000);
    }
  }

  requestGetData(
    params: {
      id?: number;
      pageSize?: number;
      current?: number;
    },
    sorter: {
      [key: string]: 'ascend' | 'descend';
    },
    filter: {
      [key: string]: React.ReactText[];
    },
  ) {
    return APIS.StatAPI.GetStatExp({...params, sorter, filter, id: this.state.filter}).then((res) => {
      var data = res.data
      const result = {
        data: data.records,
        total: data.total,
        success: true,
        pageSize: data.size,
        current: parseInt(`${data.current}`, 10) || 1,
      };
      this.setState({
        outStanding: res.data.outStanding,
        total: res.data.total,
        good: res.data.good,
      })
      return result;
    });
  }

  interval: any;

  handleUpdateModalVisible(value: boolean) {
  }

  handleUpdate(value: any) {
    return false;
  }

  clomns: any = [
    {
      title: '实验名称',
      dataIndex: 'expName',
      rules: [
        {
          required: true,
          message: '试卷名称为必填项',
        },
      ],
    },
    {
      title: '实验用户',
      dataIndex: 'trueName',
      hideInForm: true,
    },
    {
      title: '实验状态',
      dataIndex: 'status',
      render: (a, r) => {
        switch (r.status) {
          case 1:
          case 2:
            return "未完成"
          case 3:
            return "已完成"
        }
        return ""
      }
    },
    {
      title: '实验成绩',
      dataIndex: 'score',
      render: (a, r) => {

        return r.score || "0"
      }
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      hideInForm: true,
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      hideInForm: true,
      render: (a, r) => {
        return r.endTime || "---"
      }
    },
    {
      title: '实验时长',
      dataIndex: 'timeUsed',
      hideInForm: true,
      render: (a, r) => {
        if (r.endTime) {
          const timed = moment(r.endTime).diff(moment(r.startTime), 'seconds')
          return FormatTime(timed);
        } else {
          return "---";
        }
      }
    },
    {
      title: '实验报告',
      dataIndex: 'report',
      hideInForm: true,
      render: (a, record) => {
        if (record.addId) {
          return <a href={record.addId}>下载</a>
        } else {
          return <a style={{color: "#b3b3b3", cursor: "not-allowed"}}>未生成</a>
        }
      }
    },
  ];

  selectChange(item, info) {
    this.setState({expId: parseInt(info.key)});
  }

  onExport() {
    // @ts-ignore
    const {expId, startTime, endTime} = this.state;
    if (expId) {
      const data = {
        expId,
        startTime,
        endTime
      };
      APIS.StatAPI.PostExportExpStat(JSON.stringify(data)).then((resp) => {
        if (resp.code === SUCCESS_CODE && resp.data) {
          this.setState({visible: false, disable: true});
          localStorage.setItem("disable_time", (5 * 60 * 1000).toString());
          setInterval(this.CheckTime, 1000);
          DownLoadFile(resp.data);
        }
      }).catch(e => {
        console.error(e);
        message.error("导出失败");
        this.setState({visible: false});
      });
    } else {
      message.error("请填写完整信息");
    }
  }

  CheckTime = () => {
    let time = parseInt(localStorage.getItem("disable_time"));
    time -= 1000;
    localStorage.setItem("disable_time", time.toString());
    if (time <= 0) {
      localStorage.setItem("disable_time", "0");
      this.setState({disable: false});
      clearInterval(this.interval);
    }
  }

  render() {
    const {RangePicker} = DatePicker
    const {allCourse} = this.state;
    return (
      <div>
        <div style={{display: "flex", justifyContent: "space-between"}}>
          <FilterByStatistics
            placeholder={"请选择课程"}
            course={allCourse}
            getValue={(value) => {
              this.setState({filter: value});
              this.actionRef?.reload();
            }}
          >

          </FilterByStatistics>
          <div style={{float: "right", paddingTop: 10}}>
            <Button type="primary" disabled={this.state.disable} onClick={() => {
              this.setState({visible: true})
            }}>导出记录</Button>
          </div>
        </div>
        {/* <CustomCascader datasource={[{
          placeholder: "请选择课程",
          dataGet: (values) => APIS.OrgsAPI.SearchGetSchoolList({ current: 1, pageSize: 100 }), renderOption: (data) => {
            return <Select.Option key={data.id} value={data.id}>{data.name}</Select.Option>
          }
        }]}></CustomCascader> */}
        <HighPerformTable<any>
          columns={this.clomns}
          action={true}
          requestGetData={this.requestGetData.bind(this)}
          ref={(ref) => (this.actionRef = ref)}
          hideOptions={true}
        />
        <Modal
          title={"导出记录"}
          visible={this.state.visible}
          destroyOnClose={true}
          onCancel={() => this.setState({visible: false})}
          footer={<div></div>}
        >
          <Form.Item
            label='课程分类'
            name='expId'
            rules={[{required: true, message: '请选择实验id'}]}
          >
            <Select showSearch
                    onChange={this.selectChange.bind(this)}>
              {this.state.allExp.map?.((v: any, i) => {
                return <Select.Option key={v.id} value={v.expName}>{v.expName}</Select.Option>
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label='起止时间'
            name='time'
          >
            <RangePicker
              defaultValue={null}
              onChange={(date, dateString) => {
                this.setState({startTime: dateString[0], endTime: dateString[1]});
              }}
              showTime
            />
          </Form.Item>
          <div style={{display: "flex", justifyContent: "center"}}>
            <Button type="primary" onClick={this.onExport.bind(this)}>导出</Button>
          </div>

        </Modal>
      </div>
    );
  }
}

export default connect()(LearnStat);
